package com.ruoyi.foodworks.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.foodworks.domain.Likes;
import com.ruoyi.foodworks.domain.LikesVO;
import com.ruoyi.foodworks.domain.Users;
import com.ruoyi.foodworks.domain.Works;
import com.ruoyi.foodworks.service.LikesService;
import com.ruoyi.foodworks.service.UsersService;
import com.ruoyi.foodworks.service.WorksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;

/**
 * 作品点赞Controller
 * 
 * @author lpt
 * @date 2025-08-12
 */
@RestController
@Controller("foodWorksLikesController")
@RequestMapping("/likes/likes")
public class LikesController extends BaseController
{
    @Autowired
    private LikesService likesService;
    
    @Autowired
    private UsersService usersService;
    
    @Autowired
    private WorksService worksService;
    
    @Autowired
    private RedisCache redisCache;

    /**
     * 根据点赞用户ID查询用户昵称
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:list')")
    @GetMapping("/getUserNickname")
    public AjaxResult getUserNickname(@RequestParam Integer likerUid) {
        Users user = usersService.selectUsersById(likerUid);
        if (user != null) {
            return AjaxResult.success(user.getNickname());
        }
        return AjaxResult.error("用户不存在");
    }

    /**
     * 根据被点赞作者ID查询作者昵称
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:list')")
    @GetMapping("/getAuthorNickname")
    public AjaxResult getAuthorNickname(@RequestParam Integer authorUid) {
        Users user = usersService.selectUsersById(authorUid);
        if (user != null) {
            return AjaxResult.success(user.getNickname());
        }
        return AjaxResult.error("用户不存在");
    }

    /**
     * 根据作品ID查询作品内容
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:list')")
    @GetMapping("/getWorkContent")
    public AjaxResult getWorkContent(@RequestParam Integer targetId) {
        Works work = worksService.selectWorksByWorkId(targetId);
        if (work != null) {
            return AjaxResult.success(work.getContent());
        }
        return AjaxResult.error("作品不存在");
    }

    /**
     * 查询作品点赞列表
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:list')")
    @GetMapping("/list")
    public TableDataInfo list(Likes likes)
    {
        startPage();
        List<Likes> list = likesService.selectLikesList(likes);
        return getDataTable(list);
    }

    /**
     * 查询作品点赞列表（包含用户昵称和作品内容）
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:list')")
    @GetMapping("/listWithInfo")
    public TableDataInfo listWithInfo(Likes likes)
    {
        startPage();
        List<LikesVO> list = likesService.selectLikesVOList(likes);
        return getDataTable(list);
    }

    /**
     * 导出作品点赞列表
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:export')")
    @Log(title = "作品点赞", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Likes likes)
    {
        List<Likes> list = likesService.selectLikesList(likes);
        ExcelUtil<Likes> util = new ExcelUtil<Likes>(Likes.class);
        util.exportExcel(response, list, "作品点赞数据");
    }

    /**
     * 获取作品点赞详细信息
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(likesService.selectLikesById(id));
    }

    /**
     * 新增作品点赞
     */
    // 我要调用这个接口，添加数据给我模拟一条请求（带数据）
    @PreAuthorize("@ss.hasPermi('likes:likes:add')")
    @Log(title = "作品点赞", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Likes likes)
    {
        return toAjax(likesService.insertLikes(likes));
    }

    /**
     * 修改作品点赞
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:edit')")
    @Log(title = "作品点赞", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Likes likes)
    {
        return toAjax(likesService.updateLikes(likes));
    }

    /**
     * 删除作品点赞
     */
    @PreAuthorize("@ss.hasPermi('likes:likes:remove')")
    @Log(title = "作品点赞", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(likesService.deleteLikesByIds(ids));
    }

    /**
     * Redis点赞/取消点赞接口
     */
    @PostMapping("/redisLike")
    public AjaxResult redisLike(@RequestBody Likes likes)
    {
        try {
            // 参数验证
            if (likes.getLikerUid() == null || likes.getAuthorUid() == null || 
                likes.getTargetId() == null || likes.getTargetType() == null) {
                return AjaxResult.error("参数不完整");
            }
            
            // 调用service方法
            Map<String, Object> result = likesService.redisLike(
                likes.getLikerUid(), 
                likes.getAuthorUid(), 
                likes.getTargetId(), 
                likes.getTargetType().intValue()
            );
            
            // 返回结果
            if ((Boolean) result.get("success")) {
                return AjaxResult.success(result);
            } else {
                return AjaxResult.error((String) result.get("message"));
            }
            
        } catch (Exception e) {
            return AjaxResult.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户点赞状态
     */
    @PostMapping("/getUserLikeStatus")
    public AjaxResult getUserLikeStatus(@RequestBody UserLikeStatusRequest request)
    {
        try {
            List<Integer> likedIds = likesService.getUserLikeStatus(
                request.getUserId(), 
                request.getTargetIds(), 
                request.getTargetType().intValue()
            );
            return AjaxResult.success(likedIds);
        } catch (Exception e) {
            return AjaxResult.error("获取点赞状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取点赞数
     */
    @GetMapping("/getLikeCount/{targetId}/{targetType}")
    public AjaxResult getLikeCount(@PathVariable Integer targetId, @PathVariable Integer targetType)
    {
        try {
            Integer count = likesService.getLikeCount(targetId, targetType);
            return AjaxResult.success(count);
        } catch (Exception e) {
            return AjaxResult.error("获取点赞数失败：" + e.getMessage());
        }
    }

    /**
     * 批量获取点赞数
     */
    @PostMapping("/getLikeCounts")
    public AjaxResult getLikeCounts(@RequestBody Map<String, Object> request)
    {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> targetIds = (List<Integer>) request.get("targetIds");
            Integer targetType = (Integer) request.get("targetType");
            
            if (targetIds == null || targetType == null) {
                return AjaxResult.error("参数不完整");
            }
            
            Map<Integer, Integer> counts = likesService.getLikeCounts(targetIds, targetType);
            return AjaxResult.success(counts);
        } catch (Exception e) {
            return AjaxResult.error("批量获取点赞数失败：" + e.getMessage());
        }
    }

    
    /**
     * 用户点赞状态请求对象
     */
    public static class UserLikeStatusRequest {
        private Integer userId;
        private List<Integer> targetIds;
        private Long targetType;
        
        public Integer getUserId() {
            return userId;
        }
        
        public void setUserId(Integer userId) {
            this.userId = userId;
        }
        
        public List<Integer> getTargetIds() {
            return targetIds;
        }
        
        public void setTargetIds(List<Integer> targetIds) {
            this.targetIds = targetIds;
        }
        
        public Long getTargetType() {
            return targetType;
        }
        
        public void setTargetType(Long targetType) {
            this.targetType = targetType;
        }
    }
}
